import React, { useState, useRef, useEffect } from 'react';
import { 
  Button, 
  Space,
  Input,
  Modal,
  Select,
  Tabs,
  TreeSelect,
  Form,
  Cascader,
  InputNumber,
  DatePicker,
  Upload,
  message 
} from 'antd';
import {
  PlusOutlined,
  DownloadOutlined,
  UploadOutlined,
  DeleteOutlined,
  ClockCircleOutlined,
  DownOutlined,
  SearchOutlined,
  FilterOutlined,
  BorderOutlined,
  MenuUnfoldOutlined,
  SyncOutlined,
  FullscreenOutlined
} from '@ant-design/icons';
import "../../style/Xiaoshoudingdan.css";
import type { TableColumnsType } from 'antd';
import FormData from "../../Components/FormData";
import FormData1 from "../../Components/FormData1";
import type { GetProps } from 'antd';
import Table from '../../Components/Table';
import Table2 from "../../Components/Table2";
import Table3 from "../../Components/Table3";
import Table4 from "../../Components/Table4";
import * as API from '../../utils/GetData';
import SelectChengyuan from '../../Components/SelectChengyuan';
import SelectBumen from '../../Components/SelectBumen';
const { Search } = Input;
const { TabPane } = Tabs;
const { TextArea } = Input;

interface Option {
  value: string;
  label: string;
  children?: Option[];
}
interface SalesOrderFormData {
  // 销售订单基本信息
  customer: {
    id: number;
    name: string;
    code: string;
    priceLevel: string;
    contactName: string;
    contactPhone: string;
  } | null;
  customerName: string;
  customerCode: string;
  priceLevel: string;
  contactName: string;
  contactPhone: string;
  salesOrderName: string;
  deliqiandingveryDate: string | null;
  deliveryDate: string | null;
  salesOwner: {
    id: number;
    name: string;
    departmentId: number;
    departmentName: string;
  } | null;
  salesDepartment: string;
  salesOrderCode: string;
  
  // 销售产品明细
  warehouse: string;
  products: Array<{
    id: number;
    name: string;
    code: string;
    specification: string;
    unit: string;
    priceLevel: string;
    price: number;
    quantity: number;
    amount: number;
    costPrice: number;
    costAmount: number;
    profitRate: number;
  }>;
  originalAmount: number;
  discountAmount: number;
  discountRate: number;
  totalAmount: number;
  totalAmountChinese: string;
  profitRate: number;
  contractFiles: UploadFile[];
  
  // 订单明细标签页
  deliveryAddress: string[];
  detailedAddress: string;
  financialTerms: {
    terms: string;
    settlementPeriod: string;
  };
  paymentPlan: Array<{
    id: number;
    date: string;
    amount: number;
    remark: string;
  }>;
  
  // 财务明细标签页
  invoiceInfo: {
    title: string;
    taxNumber: string;
    vatRate: number;
  };
  bankAccountInfo: {
    account: string;
    bankName: string;
  };
}
const SalesOrderForm: React.FC = () => {
  const [form] = Form.useForm();
  const [activeKey, setActiveKey] = useState('1');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCustomerModalOpen, setIsCustomerModalOpen] = useState(false);
  const [isMemberModalOpen, setIsMemberModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const newTabIndex = useRef(0);

  

  const onSearch: GetProps<typeof Input.Search>['onSearch'] = (value, _e, info) => {
    console.log(info?.source, value);
  };

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    form.validateFields()
      .then(values => {
        setLoading(true);
        console.log('Form values:', values);
        // 这里可以添加API调用
        setTimeout(() => {
          setLoading(false);
          setIsModalOpen(false);
          message.success('订单创建成功');
        }, 1000);
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handleTabChange = (key: string) => {
    setActiveKey(key);
  };

  const handleCustomerSelect = (customer: any) => {
    form.setFieldsValue({
      customerName: customer.name,
      customerCode: customer.code,
      contactName: customer.contact,
      contactPhone: customer.phone
    });
    setIsCustomerModalOpen(false);
  };

  const handleMemberSelect = (member: any) => {
    form.setFieldsValue({
      salesOwner: member.name,
      salesDepartment: member.department
    });
    setIsMemberModalOpen(false);
  };

  const beforeUpload = (file: File) => {
    const isLt20M = file.size / 1024 / 1024 < 20;
    if (!isLt20M) {
      message.error('文件必须小于20MB!');
    }
    return isLt20M;
  };

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const regionOptions: Option[] = [
    // 保留原有的地区选项
    // ...
  ];
  
  const onFinish = (values:SalesOrderFormData) => {
      console.log('Success:', values);
  };


  return (
    <div>
      <Space>
        <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>
          添加
        </Button>
        <Button icon={<DownloadOutlined />}>导入</Button>
        <Button icon={<UploadOutlined />}>导出</Button>
        <Button icon={<DeleteOutlined />}>删除</Button>
        <Button icon={<ClockCircleOutlined />}>操作记录</Button>
        
        <div style={{ marginLeft: 200 }}>
          <Search
            prefix={<SearchOutlined />}
            placeholder="输入搜索内容"
            allowClear
            onSearch={onSearch}
            style={{ width: 304 }}
            suffix={<DownOutlined />}
          />
          <Button icon={<FilterOutlined />}>筛选</Button>
          <Button icon={<BorderOutlined />} />
          <Button icon={<MenuUnfoldOutlined />} />
          <Button icon={<SyncOutlined />} />
          <Button icon={<FullscreenOutlined />} />
        </div>
      </Space>

      <Table />

      <Modal
        title="销售订单"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        width={1200}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            priceLevel: '一级售价',
            salesOrderName: '帆软软软件有限公司-第1份销售订单',
            salesOrderCode: '自动生产无需填写'
          }}
        >
          <div className='ziti'>销售订单基本信息</div>
          <div className='lantiao'>
            <div className='lantiaoleft'></div>
          </div>
          <p>使用Tip：销售订单通过标签页，可以一站式完成所有销售业务流程</p>

          <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between' }}>
            <Form.Item
              label={<span><span className='yanse1'>*</span>选择客户</span>}
              name="customer"
              rules={[{ required: true, message: '请选择客户' }]}
              style={{ width: '48%' }}
            >
              <Button 
                block 
                onClick={() => setIsCustomerModalOpen(true)}
                style={{ textAlign: 'left', height: 30 }}
              >
                选择数据
              </Button>
            </Form.Item>

            <Form.Item label="客户名称" name="customerName" style={{ width: '48%' }}>
              <Input placeholder="暂无内容" disabled />
            </Form.Item>

            <Form.Item label="客户编码" name="customerCode" style={{ width: '48%' }}>
              <Input placeholder="暂无内容" disabled />
            </Form.Item>

            <Form.Item label="价格等级" name="priceLevel" style={{ width: '48%' }}>
              <Input placeholder="暂无内容" disabled />
            </Form.Item>

            <Form.Item label="客户联系人姓名" name="contactName" style={{ width: '48%' }}>
              <Input placeholder="暂无内容"  disabled/>
            </Form.Item>

            <Form.Item label="客户联系人手机" name="contactPhone" style={{ width: '48%' }}>
              <Input  placeholder="暂无内容" disabled/>
            </Form.Item>

            <Form.Item label="销售订单名称" name="salesOrderName" style={{ width: '48%' }}>
              <Input placeholder="暂无内容"  disabled/>
            </Form.Item>


            <Form.Item 
              label={<span><span className='yanse1'>*</span>订单签订日期</span>}
              name="deliqiandingveryDate"
              rules={[{ required: true, message: '请选择交付日期' }]}
              style={{ width: '48%' }}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>


            <Form.Item 
              label={<span><span className='yanse1'>*</span>订单交付日期</span>}
              name="deliveryDate"
              rules={[{ required: true, message: '请选择交付日期' }]}
              style={{ width: '48%' }}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item 
              label="销售负责人" 
              name="salesOwner" 
              style={{ width: '48%' }}
            >
              {/* <Button 
                block 
                
                style={{ textAlign: 'left', height: 30 }}
                icon={<PlusOutlined />}
              > */}
                 <SelectChengyuan ></SelectChengyuan>
              {/* </Button> */}
            </Form.Item>

            <Form.Item label="销售归属部门" name="salesDepartment" style={{ width: '48%' }}>
              <SelectBumen bumen={value=>form.setFieldsValue({department:value})}></SelectBumen>
            </Form.Item>

            <Form.Item label="销售订单编号" name="salesOrderCode" style={{ width: '48%' }}>
              <Input  />
            </Form.Item>
          </div>

          <div className='ziti'>销售产品明细</div>
          <div className='lantiao'>
            <div className='lantiaoleft'></div>
          </div>
          <p>请选择需要的产品，并在选择完毕后填写销售数量!销售单价默认联动上方价格等级价格!</p>
          <p className="yanse">毛利率低于35%,不允许通过！</p>

          <Form.Item
            label={<span><span className='yanse1'>*</span>选择仓库</span>}
            name="warehouse"
            rules={[{ required: true, message: '请选择仓库' }]}
          >
            <Select
              style={{ width: 350 }}
              options={[
                { value: 'jack', label: '杭州仓' },
                { value: 'lucy', label: '无锡仓' },
              ]}
            />
          </Form.Item>

          <Form.Item
            label={<span><span className='yanse1'>*</span>销售产品明细</span>}
            name="products"
            rules={[{ required: true, message: '请添加产品' }]}
          >
            <Table2 />
          </Form.Item>

    

          <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between' }}>
            <Form.Item label="销售原价总额(含税)/元" name="originalAmount" style={{ width: '48%' }}>
              <InputNumber  style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item 
              label="优惠金额/元" 
              name="discountAmount"
              tooltip="优惠金额默认按金额比例，均摊到各产品"
              style={{ width: '48%' }}
            >
              <InputNumber style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item 
              label="整单折扣率%" 
              name="discountRate"
              tooltip="销售订单金额(含税)/销售原价总额(含税)"
              style={{ width: '48%' }}
            >
              <InputNumber  style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item label="销售订单金额(含税)/元" name="totalAmount" style={{ width: '48%' }}>
              <InputNumber  style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item label="销售订单金额大写" name="totalAmountChinese" style={{ width: '48%' }}>
              <Input  />
            </Form.Item>

            <Form.Item 
              label={<span><span className='yanse1'>*</span>订单毛利率%</span>}
              name="profitRate"
              tooltip="(销售订单金额(含税)-产品成本总额)/销售订单金额(含税)"
              style={{ width: '48%' }}
            >
              <InputNumber  style={{ width: '100%' }} />
            </Form.Item>

            <Form.Item
              label="合同附件上传"
              name="contractFiles"
              valuePropName="fileList"
              getValueFromEvent={normFile}
              style={{ width: '100%' }}
            >
              <Upload.Dragger
                name="file"
                multiple={false}
                beforeUpload={beforeUpload}
                showUploadList={{ showRemoveIcon: true }}
              >
                <p className="ant-upload-text">点击或拖拽文件到此处上传</p>
                <p className="ant-upload-hint">单个文件20MB以内</p>
              </Upload.Dragger>
            </Form.Item>
          </div>

          <Tabs activeKey={activeKey} onChange={handleTabChange}>
            <TabPane tab="订单明细" key="1">
              <Form.Item label="送货地址" name="deliveryAddress">
                <Cascader options={regionOptions} placeholder="请选择" style={{ width: '100%' }} />
              </Form.Item>
              
              <Form.Item label="详细地址" name="detailedAddress">
                <TextArea rows={4} />
              </Form.Item>
              
              <Table3 />
              
            
              
              <Form.Item label="财务条款" name="financialTerms">
                <Input.TextArea rows={2} />
              </Form.Item>
              
              <Form.Item label="结算期限" name="settlementPeriod">
                <Input />
              </Form.Item>
              
              <Form.Item label="收款计划" name="paymentPlan">
                <Table4 />
                <div style={{ marginTop: 16 }}>
                  <Button icon={<PlusOutlined />} className='yanse2'>添加</Button>
                  <Button icon={<ClockCircleOutlined />} className='yanse2' style={{ marginLeft: 8 }}>快速填报</Button>
                </div>
              </Form.Item>
            </TabPane>
            
            <TabPane tab="财务明细" key="2">
              <div>开票明细</div>
              <div style={{ width: "100%", display: 'flex', flexWrap: "wrap", justifyContent: "space-between" }}>
                <Form.Item label="发票抬头" name="invoiceTitle" style={{ width: '48%' }}>
                  <Input />
                </Form.Item>
                
                <Form.Item label="发票税号" name="invoiceTaxNumber" style={{ width: '48%' }}>
                  <Input />
                </Form.Item>
                
                <Form.Item label="增值税税率%" name="vatRate" style={{ width: '48%' }}>
                  <Input />
                </Form.Item>
              </div>
              
              <div>银行账户明细</div>
              <div style={{ width: "100%", display: 'flex', flexWrap: "wrap", justifyContent: "space-between" }}>
                <Form.Item label="银行账户" name="bankAccount" style={{ width: '48%' }}>
                  <Input />
                </Form.Item>
                
                <Form.Item label="开户银行" name="bankName" style={{ width: '48%' }}>
                  <Input />
                </Form.Item>
              </div>
            </TabPane>
            
            <TabPane tab="销售出库" key="3">
              销售出库内容
            </TabPane>
            
            <TabPane tab="销售退换货" key="4">
              销售退换货内容
            </TabPane>
            
            <TabPane tab="销售订单执行追踪" key="5">
              销售订单执行追踪内容
            </TabPane>
          </Tabs>
          <Form.Item label={null}>

              <Button type="primary" htmlType="submit"> 提交</Button>
          </Form.Item>
        </Form>
        
      </Modal>

      {/* 客户选择模态框 */}
      <Modal
        title="选择客户"
        width={1200}
        open={isCustomerModalOpen}
        onCancel={() => setIsCustomerModalOpen(false)}
        footer={null}
      >
        <FormData onSelect={handleCustomerSelect} />
      </Modal>
       
      {/* 成员选择模态框 */}
      {/* <Modal
        title="选择成员"
        width={1200}
        open={isMemberModalOpen}
        onCancel={() => setIsMemberModalOpen(false)}
        footer={null}
      > */}
       
      {/* </Modal> */}

{/* 
        <Modal
        title="选择部门"
        width={1200}
        open={isMemberModalOpen}
        onCancel={() => setIsMemberModalOpen(false)}
        footer={null}
      > 
        <SelectBumen></SelectBumen>
       </Modal> */}


    </div>
  );
};

export default SalesOrderForm;